﻿using System;
using System.Reflection;
using System.Windows.Forms;

namespace Tilver.Coder.Win
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            //LoadResource.RegistDLL();
            //if (!ImportDLL())
            //{
            //    MessageBox.Show("DLL import error!");
            //    return;
            //}  
            //AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMain());
        }

        static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string dllName = args.Name.Contains(",") ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");

            dllName = dllName.Replace(".", "_");

            if (dllName.EndsWith("_resources")) return null;
            object localobj = new object();

            System.Resources.ResourceManager rm = new System.Resources.ResourceManager(localobj.GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

            byte[] bytes = (byte[])rm.GetObject(dllName);

            return System.Reflection.Assembly.Load(bytes);
        }  

        static bool ImportDLL()
        {
            try
            {
                AppDomain.CurrentDomain.AssemblyResolve += (sender, senderargs) =>
                {
                    var executingAssembly = Assembly.GetExecutingAssembly();
                    var assemblyName = new AssemblyName(executingAssembly.FullName).Name;
                    var dllName = new AssemblyName(senderargs.Name).Name;
                    var dllUri = assemblyName + ".reference." + dllName + ".dll";
                    //                var dllUri = assemblyName + "." + dllName + ".dll";  
                    using (var resourceStream = executingAssembly.GetManifestResourceStream(dllUri))
                    {
                        var assemblyData = new Byte[resourceStream.Length];
                        resourceStream.Read(assemblyData, 0, assemblyData.Length);
                        return Assembly.Load(assemblyData); //加载dll  
                    }
                };
                return true;
            }
            catch (System.Exception e)
            {
                return false;
            }
        }  
    }
}
